package com.atguigu.guli.api.gateway.filter;

import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.google.gson.Gson;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

//统计鉴权filter：验证用户是否登陆成功
//所以的路由  需要鉴权的接口都进行鉴权
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //过滤方法： 所有的请求访问网关项目时都会被当前过滤器调用 filter方法 处理
        //1、判断请求路径中是否包含 /auth/
        ServerHttpRequest request = exchange.getRequest();//请求对象
        ServerHttpResponse response = exchange.getResponse();//响应对象

        String path = request.getURI().getPath();//获取端口号后面的?前面的路径地址
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/api/**/auth/**", path);//参数1：代表ant格式字符串  参数2：需要验证的路径
        if(!match){
            //3、否则 放行请求
            return chain.filter(exchange);
        }
        //2 如果包含 进行鉴权
        String token = request.getHeaders().getFirst("token");
        boolean b = JwtHelper.checkToken(token);
        if (b){
            //2.2 如果鉴权成功，代表用户已登录，放行
            return chain.filter(exchange);
        }
        //2.1 如果鉴权失败，代表用户未登录，相应需要登录
        //响应一个R对象 的json，内容为需要登录
        Map map = new HashMap();
        map.put("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        map.put("success",ResultCodeEnum.LOGIN_AUTH.getSuccess());
        map.put("message","网关项目鉴权失败的响应");

        String json = new Gson().toJson(map);
        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes());
        response.getHeaders().set("content-type","application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));//body代表响应体内容
    }

    //决定filter执行的优先级，值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
